package hch.utils;

import hch.redesFerroviarias.Pasajero;

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Buffer {
	
	private ArrayList<Pasajero> buffer = new ArrayList();
	private Lock lock = new ReentrantLock();
	private Condition condAdd = lock.newCondition();	
	private Condition condRem = lock.newCondition();

	
	
	public void add(Pasajero p) {
		lock.lock();
		buffer.add(p);
		condRem.signal();
		lock.unlock();
	}
	
	
	public Pasajero remove() {
		lock.lock();
		while (size() == 0) {
			try { condRem.await(); }
			catch (InterruptedException e) {}
		}
		Pasajero p = buffer.get(0);
		buffer.remove(0);
		condAdd.signal();
		lock.unlock();
		return p;
	}
	
	
	public int size() {
		lock.lock();
		int size = buffer.size();
		lock.unlock();
		return size;
	}
	
}
